package com.polaris.live.ui.party.fragment.roomInfo

import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.FragmentSpectatorRoomInfoBinding
import com.polaris.live.interface_bag.PAGViewListener
import com.polaris.live.net.liveService
import com.polaris.live.net.userService
import com.polaris.live.popup.party.ExitMemberPopup
import com.polaris.live.popup.party.JoinMemberPopup
import com.polaris.live.resp.back_resp.PartyRoomInfoResp
import com.polaris.live.resp.go_resp.OtherUserIdBean
import com.polaris.live.translation.R
import com.polaris.live.utils.BitwiseUtils
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.pag.AddFollowView
import org.libpag.PAGScaleMode
import org.libpag.PAGView

/**
 * SpectatorRoomInfoFragment 观众的房间资料
 *
 * @author Created by 天晴 on 2024/10/16 14:42
 * @since 1.0.0
 **/
class SpectatorRoomInfoFragment : BaseVbFragment<BaseViewModel, FragmentSpectatorRoomInfoBinding>() {

    private var isMember = false //是不是成员

    private val mUserId by lazy {
        arguments?.getLong("userId", 0) ?: 0
    }
    private val mRoomId by lazy {
        arguments?.getString("roomId") ?: ""
    }
    private var mPartyRoomInfoResp: PartyRoomInfoResp? = null

    private var avBack: (() -> Unit)? = null
    override fun initView(savedInstanceState: Bundle?) {
        mPartyRoomInfoResp?.let {
            setDataView(it)
        }
        getInfoUser()
        initListener()
    }

    private fun initListener() {
        mBinding.avCl.setOnClickListener {
            avBack?.invoke()
        }
        mBinding.addFollow.setOnSingleClickListener {
            addLiveFollow()
        }
        mBinding.joinBtn.setOnSingleClickListener {
            mPartyRoomInfoResp?.let {
                if (isMember) {
                    ExitMemberPopup.show(requireContext(), it.cover, it.roomName) {
                        membersQuit()
                    }
                } else {
                    if (it.memberPrice == 0L) { //设置0加入直接加入，不弹窗
                        JoinMemberPopup.joinMembers(mViewModel, mRoomId, {
                            isMember = true
                            updateMemberBtn()
                            onJoinMemberCallback?.invoke(true)
                        }, { err ->
                            ToastGravity.showGravity(err.errorMsg)
                        })
                    } else {
                        JoinMemberPopup.show(
                            requireContext(),
                            mViewModel,
                            mRoomId,
                            it.memberPrice,
                            it.cover,
                            it.roomName,
                            {

                            }) {
                            isMember = true
                            updateMemberBtn()
                            onJoinMemberCallback?.invoke(true)
                        }
                    }
                }
            }
        }
    }

    fun getInfoUser() {
        val bitType = BitwiseUtils.bitwiseOperation(longArrayOf(UserManager.RELATIONSHIP_INFORMATION))
        mViewModel.request(
            { userService.getInfoOther(mUserId, bitType) },
            {
                if (it.relation?.followed == true) {
                    mBinding.addFollow.visibility = BottomPopupView.GONE
                } else {
                    mBinding.addFollow.visibility = BottomPopupView.VISIBLE
                    mBinding.addFollow.setPathType(AddFollowView.LIVE_ADD_FOLLOWE)
                }
            }
        )
    }

    fun setDataView(mPartyRoomInfoResp: PartyRoomInfoResp) {
        this.mPartyRoomInfoResp = mPartyRoomInfoResp
        withLoaded {
            mBinding.apply {

                tvNickname.text = mPartyRoomInfoResp.user.nickname
                val color = RichCharmImgUtil.serColor2HexColor(mPartyRoomInfoResp.user.nicknameColor)
                    ?: ColorUtils.getColor(com.polaris.live.R.color.white)
                tvNickname.setTextColor(color)
                vipView.setVipLevel(mPartyRoomInfoResp.user.vipLevel)
                avAvatar.setImageUrl(mPartyRoomInfoResp.user.avatar)
                avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(mPartyRoomInfoResp.user.avatarFrame))
                lvLevel.setRichsLevel(mPartyRoomInfoResp.user.richs)
                lvLevel2.setCharmsLevel(mPartyRoomInfoResp.user.charms)
                sexView.setSexAndAge(mPartyRoomInfoResp.user.sex, mPartyRoomInfoResp.user.birthday)
                if (mPartyRoomInfoResp.user.country.isNullOrEmpty() && mPartyRoomInfoResp.user.secondLanguage.isNullOrEmpty()) {
                    clLl.visibility = BottomPopupView.GONE
                } else {
                    clLl.visibility = BottomPopupView.VISIBLE
                    cvCountry.setCountry(mPartyRoomInfoResp.user.country)
                    languageView.setLanguage(mPartyRoomInfoResp.user.secondLanguage)
                }
                welcomeTv.text = mPartyRoomInfoResp.welcomeSpeech ?: StringUtils.getString(R.string.welcome_tips)
                isMember = mPartyRoomInfoResp.isMember
                updateMemberBtn()
            }
        }

    }

    private fun updateMemberBtn() {
        mBinding.apply {
            joinBtn.visibility = View.VISIBLE
            if (isMember) {
                joinBtn.text = StringUtils.getString(R.string.exit_room_members)
                joinBtn.setTextColor(ColorUtils.getColor(com.polaris.live.R.color.black))
                joinBtn.setBackgroundResource(com.polaris.live.R.drawable.r40_back_f8f9fa_stroke_1)
            } else {
                joinBtn.text = StringUtils.getString(R.string.price_join)
                joinBtn.setTextColor(ColorUtils.getColor(com.polaris.live.R.color.black))
                joinBtn.setBackgroundResource(com.polaris.live.R.drawable.close_bg_answer)
            }

        }
    }

    private fun addLiveFollow() {
        mViewModel.requestLoading(
            { userService.addFollower(OtherUserIdBean(mUserId)) },
            {
                mBinding.addFollow.apply {
                    setRepeatCount(1)
                    addListener(object : PAGViewListener {
                        override fun onAnimationEnd(p0: PAGView?) {
                            super.onAnimationEnd(p0)
                            mBinding.addFollow.visibility = View.GONE
                        }
                    })
                    setScaleMode(PAGScaleMode.Zoom)
                    play()
                }
            },
            { ToastGravity.showGravity(it.errorMsg) }
        )
    }

    /**
     * 退出成员
     */
    private fun membersQuit() {
        mViewModel.requestLoading(
            { liveService.membersQuit(mRoomId) }, {
                ToastGravity.showGravity(R.string.exit_successful)
                isMember = false
                updateMemberBtn()
                onJoinMemberCallback?.invoke(false)
            },
            { ToastGravity.showGravity(it.errorMsg) }
        )
    }

    fun setListener(avBack: () -> Unit) {
        this.avBack = avBack

    }

    private var onJoinMemberCallback: ((Boolean) -> Unit)? = null

    fun setOnJoinMemberCallback(l: (Boolean) -> Unit) {
        onJoinMemberCallback = l
    }
}